import { getCartList } from "../../apis/cart";
import { addOrder } from "../../apis/order";
import Toast from "@vant/weapp/toast/toast";

Page({
  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    allPrice: 0,
  },

  async getList() {
    const res = await getCartList();
    console.log(res);
    this.setData({
      list: res.map((item) => ({
        ...item,
        check: false,
      })),
    });
  },

  onChange(e) {
    console.log(e);
    const id = e.currentTarget.dataset.id;
    const val = e.detail;

    const list = JSON.parse(JSON.stringify(this.data.list));
    const target = list.find((item) => item.id === id);

    target.check = val;
    this.setData({
      list: list,
      allPrice: list
        .filter((item) => item.check)
        .map((item) => item.goodsNum * item.goods.goodsPrice * 100)
        .reduce((a, b) => a + b, 0),
    });
  },
  async onSubmit() {
    await addOrder({
      goodsList: this.data.list
        .filter((item) => item.check)
        .map((item) => ({
          goodsId: item.goodsId,
          goodsNum: item.goodsNum,
        })),
    });
    Toast.success("加入订单成功");
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});
